package com.cjkj.equipment.job;

import com.cjkj.common.utils.DateUtils;
import com.cjkj.equipment.domain.THospitalEquipmentCount;
import com.cjkj.equipment.mapper.EquipmentCountMapper;
import com.cjkj.equipment.mapper.THospitalEquipmentCountMapper;
import com.cjkj.hospital.domain.THospitalUser;
import com.cjkj.hospital.mapper.THospitalUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Component
@Slf4j
public class EquipmentCountJob {

    @Resource
    private THospitalUserMapper tHospitalUserMapper;

    @Resource
    private EquipmentCountMapper equipmentCountMapper;

    @Resource
    private THospitalEquipmentCountMapper tHospitalEquipmentCountMapper;

    /**
     * 每天统计上一天的设备使用次数
     * 凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void doCount() {

        log.info("开始统计设备使用次数!");

        // 获取昨天日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = calendar.getTime();
        log.info("统计日期：{}", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, yesterday));

        // 查询所有的医生账号
        List<THospitalUser> tHospitalUsers = tHospitalUserMapper.selectAllDoctorUsers();
        // 遍历医生，查询医生开单数据
        for (THospitalUser user : tHospitalUsers) {
            if(user == null) {
                continue;
            }

            // 睡眠垫使用次数
            int m = equipmentCountMapper.selectMattressUse(user.getHospitalId(), user.getDeptId(), user.getUserId(), yesterday);
            // 多参数监测仪使用次数
            int b = equipmentCountMapper.selectBraceletUse(user.getHospitalId(), user.getDeptId(), user.getUserId(), yesterday);
            if(m > 0 || b > 0) {
                THospitalEquipmentCount countInfo = new THospitalEquipmentCount();
                countInfo.setCountDate(yesterday);
                countInfo.setHospitalId(user.getHospitalId());
                countInfo.setDeptId(user.getDeptId());
                countInfo.setUserId(user.getUserId());
                countInfo.setTj01UseTimes(m);
                countInfo.setTj02UseTimes(b);
                tHospitalEquipmentCountMapper.insertTHospitalEquipmentCount(countInfo);
            }
        }

        log.info("结束统计设备使用次数!");
    }
}
